package com.medranocg.gd

import java.util.Calendar

class DocumentType {

    static belongsTo = FileType
    static hasMany = [fileTypes:FileType]
    String shortName
    String name
    Boolean versionable
    Boolean purgeable
    Boolean hasExpiration
    Integer daysInAdvanceForNotice
    Integer defaultLastingMonths
    String uploadNotificationEmailAddress

    static constraints = {
        shortName blank: false, unique: true, validator: { val, obj ->  
            def isUsed = { 
                def document = Document.withNewSession { 
                   Document.find { documentType.id == obj.id } 
                }
                document != null
            }    
            if (obj.id) {
                def oldValue = obj.getPersistentValue('shortName')
                if (oldValue != val && isUsed()) {
                    return ['shortNameUsed', [oldValue]]
                }
            }
            if (!(val ==~ /[a-zA-Z0-9\-_]+/)) {
                return ['notAllowedChars']
            }
        }
        uploadNotificationEmailAddress nullable: true, email: true
        defaultLastingMonths nullable: false, blank: false
        daysInAdvanceForNotice range: 1..1000
        defaultLastingMonths range: 1..9999
    }

	static mapping = {
		table 'gdca_documentType'
        fileTypes(joinTable: [name: 'gdca_fileType_documentType'])
	}
	
    def String toString() {
        name
    }

    def Date defaultExpirationDay(now) {
        def calendar = Calendar.getInstance()
        calendar.setTime(now)
        calendar.add(Calendar.MONTH, defaultLastingMonths)
        calendar.getTime()
    }

    def Boolean mustSendNotificationOnUpload() {
        uploadNotificationEmailAddress != null
    }

}
